package online.hxstar.learn.chapter4;

import lombok.extern.slf4j.Slf4j;
import online.hxstar.learn.chapter2.EchoServer;

import java.io.IOException;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;

/**
 * @author xinghu
 * @version 1.0
 * @date 2019/11/7 6:35 下午
 */
@Slf4j
public class PlainOioServer {
	public static void main(String[] args) throws InterruptedException, IOException {
		Scanner scanner = new Scanner(System.in);
		int num = scanner.nextInt();
		if (num != 0) {
			log.error("Usage: " + EchoServer.class.getSimpleName() + " <port>");
		} else {
			log.error("Usage: " + num + " <port>");
		}
		new PlainOioServer().start(num);
	}

	private void start(int num) throws IOException {

		final ServerSocket socket = new ServerSocket();

		try {
			for (; ; ) {
				final Socket clientSocket = socket.accept();
				new Thread(new Runnable() {
					public void run() {
						OutputStream out;
						try {
							out = clientSocket.getOutputStream();
							out.write("Hi!\r\n".getBytes());
						} catch (IOException e) {
							e.printStackTrace();
						} finally {
							try {
								clientSocket.close();
							} catch (IOException e) {
								e.printStackTrace();
							}
						}
					}
				}).start();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}
